<template>
    <div class="container">
        <HeaderNav/>
        <div class="login-wrapper">
            <el-tabs stretch type="border-card" v-model="activeName">
                <el-tab-pane label="登录" name="first">
                    <div class="login-item">
                        <el-form status-icon ref="loginForm" :model="loginForm" :rules="rules">
                            <el-form-item prop="phone">
                                <el-input placeholder="手机号码" v-model="loginForm.phone"></el-input>
                            </el-form-item>
                            <el-form-item prop="password">
                                <el-input placeholder="密码" type="password" v-model="loginForm.password"
                                          @keyup.enter.native="login('loginForm')"></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="login('loginForm')">登录</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="注册" name="second">
                    <div class="login-item">
                        <el-form status-icon :rules="rules" ref="logupForm" :model="logupForm">
                            <el-form-item prop="username">
                                <el-input placeholder="昵称" v-model="logupForm.username"></el-input>
                            </el-form-item>
                            <el-form-item prop="phone">
                                <el-input placeholder="手机号码" v-model="logupForm.phone"></el-input>
                            </el-form-item>
                            <el-form-item prop="pass">
                                <el-input placeholder="密码" type="password" v-model="logupForm.password"></el-input>
                            </el-form-item>
                            <el-form-item prop="checkPass">
                                <el-input placeholder="再次确认密码" type="password" v-model="logupForm.checkPass"
                                          @keyup.enter.native="submitForm('logupForm')"></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="success" v-loading.fullscreen.lock="fullscreenLoading"
                                           @click="submitForm('logupForm')">注册
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template>


<script>
    import {setToken, getToken} from '@/utils/auth'

    import HeaderNav from '@/components/HeaderNavbar'
    import {logup,login, doLogIn, wrongPass, wrongUser, logUpSucc} from '@/api/login'
    import {mapMutations} from 'vuex';
    export default {
        name: "Login",
        data() {
            var checkPhone = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('手机号码不能为空'));
                }
                setTimeout(() => {
                    if (typeof Number.isInteger(value) != Number) {
                        if (value.length != 11) {
                            callback(new Error('手机格式错误'));
                        } else {
                            callback();
                        }
                    }
                }, 1000);
            };
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.logupForm.checkPass !== '') {
                        this.$refs.logupForm.validateField('checkPass');
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.logupForm.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                token: '',
                info:'',
                fullscreenLoading: false,
                activeName: 'first',
                loginForm: {
                    phone: '',
                    password: ''
                },
                logupForm: {
                    username: '',
                    phone: '',
                    password: '',
                    checkPass: ''
                },
                rules: {
                    username: [
                        {required: true, message: '请输入昵称', trigger: 'blur'},
                        {min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur'}
                    ],
                    phone: [
                        {validator: checkPhone, trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '密码不能为空', trigger: 'blur'}
                    ],
                    pass: [
                        {validator: validatePass, trigger: 'blur'}
                    ],
                    checkPass: [
                        {validator: validatePass2, trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
            ...mapMutations(['saveToken','saveUser']),
            //  登录
            login(name) {
                login(this.loginForm).then(res => {
                    console.log(res);
                    setToken(res.data.data.token)
                    this.logInSucc(res.data)
                })
            },
            logInSucc(res) {
                //加载中 动画
                this.fullscreenLoading = true;
                setTimeout(() => {
                    this.fullscreenLoading = false;
                }, 1000);
                console.log(res);
                if (res) {
                    let _this = this;
                    //  用户名输入错误
                    if (res.code === '40004') {
                        _this.fullscreenLoading = true;
                        setTimeout(() => {
                            _this.fullscreenLoading = false;
                        }, 500);
                        _this.$message({
                            message: '用户不存在',
                            type: 'warning'
                        });
                    }
                    //  密码输入错误
                    if (res.code === '30001') {
                        _this.fullscreenLoading = true;
                        setTimeout(() => {
                            _this.fullscreenLoading = false;
                        }, 500);
                        _this.$message({
                            message: '密码错误',
                            type: 'warning'
                        });
                    }
                    //  登录成功
                    if (res.code === '20001') {

                        //  获取用户信息
                        _this.token = res.data.token.token;
                        _this.info = res.data.userInfo

                        // vuex mutations 设置token userInfo
                        _this.saveToken({token: _this.token});
                        _this.saveUser({info: _this.info})
                        _this.$store.state.isLogin = true;

                        //  登录成功跳转首页
                        _this.$router.push('/');
                        _this.$message({
                            message: '登录成功',
                            type: 'success'
                        });
                    }
                }
            },
            //  注册
            submitForm(formName) {
                let _this = this;
                console.log(this.logupForm);
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        _this.axios.post('/api/logup',_this.logupForm)
                            .then(_this.logUpSucc)
                            .catch(err => {
                                console.log(err);
                            })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            logUpSucc(res) {
                if(res.data.code === '10001') {
                    this.$message({
                        message: '用户名已经有人使用了',
                        type: 'error'
                    });
                }
                if(res.data.code === '10002') {
                    this.$message({
                        message: '手机已经有人使用了',
                        type: 'error'
                    });
                }
                if (res && res.data.code === '20000') {
                    //加载中 动画
                    this.fullscreenLoading = true;
                    setTimeout(() => {
                        this.fullscreenLoading = false;
                    }, 1000);
                    //让选项卡 回到登录
                    this.activeName = "first";
                    this.$message({
                        message: '注册成功',
                        type: 'success'
                    });
                }
            }
        },
        components: {
            HeaderNav
        }
    }
</script>

<style lang="stylus" scoped>
    @import "~@/assets/styles/css/variable.styl"
    .login-wrapper >>> .el-tabs__item.is-active
        color: $themeColor;

    .login-wrapper >>> .el-tabs__active-bar
        background: $themeColor;

    .login-wrapper >>> .el-tabs__item:hover
        color: $themeColor !important;

    .login-wrapper >>> .el-tabs__content
        padding: 15% 10%;

    .login-wrapper >>> .el-form-item__content .el-button--success
        width: 100%;

    .login-wrapper >>> .el-form-item__content .el-button--primary
        width: 100%;
        background: $themeColor;
        border: $themeColor;

    .login-wrapper
        padding: 5% 35%;
</style>